#ifndef __TOYM__BASE__FILE_H__
#define __TOYM__BASE__FILE_H__

#include <cstdio>
#include <cassert>
#include <sys/stat.h>

namespace toym
{

class File {
public:
    
    // 构造和析构

    File()
        : m_fp(nullptr),
          m_bytesWrited(0UL)
    {}

    explicit 
    File(FILE* fp)
        : m_fp(fp),
          m_bytesWrited(0UL)
    {}

    ~File() {
        close();
    }

    // API 相关
    int getFileno() {
        return ::fileno(m_fp);
    }

    std::size_t fileSize() {
        return m_bytesWrited;
    }
    
    void openWrite(const char* fname) {
        close();
        m_fp = std::fopen(fname, "w");
    }

    void write(const char* buf, std::size_t sz) {
        assert(m_fp != nullptr);
        std::fwrite(buf, 1, sz, m_fp);
        m_bytesWrited += sz;
    }

    void flush() {
        assert(m_fp != nullptr);
        std::fflush(m_fp);
    }

    void reset(FILE* fp) {
        close();
        m_fp = fp;
    }

    void close() {
        if (nullptr != m_fp)
            std::fclose(m_fp);
        m_fp = nullptr;
        m_bytesWrited = 0;
    }

    FILE* data() {
        return m_fp;
    }
private:
    std::FILE* m_fp;
    std::size_t m_bytesWrited;
};

} // namespace toym


#endif //__TOYM__BASE__FILE_H__